﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEx.Controllers;
using MvcEx.Configuration;
using System.Reflection;

namespace MvcEx
{
    public static class MvcExControllerBuilderConfigurationFactory
    {
        public static MvcExControllerBuilderConfiguration CreateBuilderConfigurationFromApplication(IMvcExApplication application, MvcExConfiguration configuration)
        {
            // We need a list of assembly names to give to the controller builder
            List<string> assemblyNames = new List<string>();

            // Loop through all the modules loaded in this configuration
            foreach (var configModule in configuration.Modules)
            {
                // Get the module specified by the configuration
                var module = application.GetModuleById(configModule.Name);

                // Go through all the assemblies this module wants
                foreach (var moduleAssembly in module.Assemblies)
                {
                    // Don't include duplicates
                    if (assemblyNames.Contains(moduleAssembly.Name)) { continue; }

                    // And add it to the list
                    assemblyNames.Add(moduleAssembly.Name);
                }
            }

            // From this we can start loading in assemblies
            MvcExControllerBuilderConfiguration builderConfiguration = new MvcExControllerBuilderConfiguration();

            // Set this for debugging purposes
            builderConfiguration.BuilderIdentifier = configuration.Id;

            foreach (String assemblyString in assemblyNames)
            {
                // Load the assembly by name
                var assembly = Assembly.Load(assemblyString, Assembly.GetExecutingAssembly().Evidence);

                // And register it with the configuration
                builderConfiguration.RegisterAssembly(assembly);
            }
            return builderConfiguration;
        }
    }
}
